<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 表单区域 -->
      <van-form @submit="onSubmit" class="login-form">
        <h2 class="form-title">登录</h2>

        <van-cell-group inset>
          <!-- 手机号输入框 -->
          <van-field v-model="formData.mobile" name="mobile" placeholder="请输入手机号" :rules="phoneRules" maxlength="11"
            :formatter="value => value.replace(/[^\d]/g, '')">
            <template #left-icon>
              <van-icon name="phone-o" class="field-icon" />
            </template>
            <template #input>
              <div class="custom-input">
                <input v-model="formData.mobile" type="tel" maxlength="11" placeholder="请输入手机号" />
              </div>
            </template>
          </van-field>

          <!-- 密码输入框 -->
          <van-field v-model="formData.password" type="password" name="password" placeholder="请输入密码"
            :rules="passwordRules" maxlength="20">
            <template #left-icon>
              <van-icon name="lock" class="field-icon" />
            </template>
            <template #input>
              <div class="custom-input">
                <input v-model="formData.password" type="password" maxlength="20" placeholder="请输入密码" />
              </div>
            </template>
          </van-field>

          <!-- 图形验证码输入框 -->
          <van-field v-model="formData.code" name="code" placeholder="请输入验证码" :rules="captchaRules" maxlength="4">
            <template #left-icon>
              <van-icon name="shield-o" class="field-icon" />
            </template>
            <template #input>
              <div class="custom-input">
                <input v-model="formData.code" type="text" maxlength="4" placeholder="请输入验证码" />
              </div>
            </template>
            <template #button>
              <div class="captcha-img" @click="refreshCaptcha">
                <img :src="captchaUrl" alt="验证码" />
              </div>
            </template>
          </van-field>
        </van-cell-group>

        <!-- 登录按钮 -->
        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>

        <!-- 其他操作区域 -->
        <div class="action-links">
          <span @click="toRegister">注册账号</span>
          <span class="divider">|</span>
          <span @click="toForgetPassword">忘记密码？</span>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { login, getCaptcha } from '@/api/user/user'
import { tim, TIM } from '@/tim'

const router = useRouter()
const userID = ref('')
const userSig = ref('')

// 表单数据
const formData = ref({
  mobile: '',
  password: '',
  code: '',
  code_key: ''
})

// 验证规则
const phoneRules = [
  { required: true, message: '请填写手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
]

const passwordRules = [
  { required: true, message: '请填写密码' },
  { min: 6, max: 20, message: '密码长度需在6-20位之间' }
]

const captchaRules = [
  { required: true, message: '请填写验证码' },
  { pattern: /^[a-zA-Z0-9]{4}$/, message: '验证码格式不正确' }
]

// 图形验证码相关
const captchaUrl = ref('')

// 刷新验证码
const refreshCaptcha = async () => {
  let res = await getCaptcha();

  // TODO: 替换为实际的验证码接口地址
  captchaUrl.value = res.imageBase64
  formData.value.code_key = res.key
}


// 提交表单
const onSubmit = async () => {
  try {
    // 调用登录接口
    let res = await login(formData.value)
    if (res.code === 200) {
      // 确保从后端获取的 userID 和 userSig 是字符串类型
      userID.value = String(res.data.id)  // 转换为字符串
      userSig.value = String(res.data.userSig)  // 转换为字符串
      
      console.log('登录参数:', {
        userID: userID.value,
        userSig: userSig.value
      })

      // 登录成功后的处理
      await handleLoginSuccess(res.data)
    } else {
      showToast(res.message || '登录失败')
      refreshCaptcha()
    }
  } catch (error) {
    console.error('登录错误:', error)
    showToast('登录失败')
    refreshCaptcha()
  }
}

  // 跳转注册页面
  const toRegister = () => {
    router.push('/register')
  }

  // 跳转忘记密码页面
  const toForgetPassword = () => {
    router.push('/forget-password')
  }

  onBeforeMount(async () => {
    try {
      // 清除存储的信息
      sessionStorage.clear()
      // 如果已登录则登出
      try {
        const profile = await tim.getMyProfile()
        if (profile.data?.userID) {
          await tim.logout()
        }
      } catch (error) {
        // 如果获取 profile 失败，说明未登录，忽略错误
        console.log('未登录状态')
      }
    } catch (error) {
      console.error('登出错误:', error)
    } finally {
      refreshCaptcha()
    }
  })

  // 登录成功后的处理
  const handleLoginSuccess = async (data) => {
    try {
      // 存储登录信息
      sessionStorage.setItem('token', data.token)
      sessionStorage.setItem('user', JSON.stringify(data))
      sessionStorage.setItem('im_user', JSON.stringify({
        userID: String(data.id),
        userSig: data.userSig
      }))

      // 等待 SDK ready
      await new Promise((resolve, reject) => {
        function onSDKReady() {
          tim.off(TIM.EVENT.SDK_READY, onSDKReady)
          tim.off(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
          resolve()
        }

        function onSDKNotReady() {
          tim.off(TIM.EVENT.SDK_READY, onSDKReady)
          tim.off(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
          reject(new Error('SDK not ready'))
        }

        // 先注册事件监听
        tim.on(TIM.EVENT.SDK_READY, onSDKReady)
        tim.on(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)

        // 尝试登录
        tim.login({
          userID: String(data.id),
          userSig: data.userSig
        }).catch(error => {
          console.error('登录失败:', error)
          reject(error)
        })

        // 设置超时
        setTimeout(() => reject(new Error('SDK ready 超时')), 5000)
      })

      // 跳转到首页
      router.push('/home')
    } catch (error) {
      console.error('登录失败:', error)
      showToast('登录失败，请重试')
    }
  }

</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  padding: 20px;
}

.login-box {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 30px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.form-title {
  text-align: center;
  font-size: 24px;
  color: #323233;
  margin: 0 0 30px;
  font-weight: 500;
}

:deep(.van-cell-group) {
  background-color: #f5f6f7;
  border-radius: 8px;
  margin-bottom: 24px;
}

:deep(.van-field) {
  background-color: transparent;
}

.field-icon {
  color: #969799;
}

.submit-btn {
  margin: 24px 0;
}

:deep(.van-button--primary) {
  background: #1989fa;
  height: 44px;
  font-size: 16px;
}

.action-links {
  text-align: center;
  font-size: 14px;
  color: #969799;
}

.action-links span {
  display: inline-block;
  padding: 0 12px;
  color: #576b95;
  cursor: pointer;
}

.action-links .divider {
  color: #ebedf0;
  cursor: default;
}

/* 添加点击效果 */
.action-links span:active {
  opacity: 0.7;
}

.custom-input {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}

.custom-input input {
  width: 100%;
  height: 24px;
  border: none;
  outline: none;
  background: transparent;
  font-size: 14px;
  color: #323233;
  padding: 0;
}

.custom-input input::placeholder {
  color: #969799;
}

:deep(.van-field__left-icon) {
  margin-right: 8px;
}

:deep(.van-field) {
  padding: 10px 16px;
}

.field-icon {
  font-size: 16px;
  color: #969799;
}

/* 添加图形验证码样式 */
.captcha-img {
  height: 32px;
  width: 100px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.captcha-img img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

/* 调整验证码字段右侧按钮的样式 */
:deep(.van-field__button) {
  padding-left: 12px;
}
</style>